<?php
declare (strict_types=1);

namespace lc\middleware;

use think\facade\Config;
use lc\PreInstall;

class LoadDb
{
    public function handle($request, \Closure $next)
    {
        $id = Config::get('lc.database.id');
        if (!$id) {
            return $next($request);
        }
        $config = PreInstall::get('database', $id);
        $config = array_merge($config, Config::get('lc.database'));
        if ($config && is_array($config)) {
            $driver = Config::get('database.default');
            $data   = Config::get('database.connections.' . $driver);
            foreach ($config as $key => $val) {
                $data[$key] = $val;
            }
            $mainConf = array_merge(['type' => 'mysql'], PreInstall::get('database', 'main'));

            Config::set(['connections' => [$driver => $data, 'main' => $mainConf]], 'database');
        }
        return $next($request);
    }
}
